package com.zwy.ubts.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yg.yws.annotation.YWebPath;
import com.yg.yws.annotation.YWebServlet;
import com.yg.yws.beans.RetType;
import com.zwy.ubts.bean.Address;
import com.zwy.ubts.bean.User;
import com.zwy.ubts.service.AddressService;
import com.zwy.ubts.service.impl.AddressServiceImpl;
import com.zwy.ubts.utils.RetJsonUtils;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * @Author Zhou Wenying
 * @Description:
 * @Date Created in 21:30 2023/3/28
 */

@YWebServlet
public class AddressController {
    private AddressService addressService = new AddressServiceImpl();

    @YWebPath("/getAddress")
    public RetType getAddress(HttpSession session){
        User user = (User) session.getAttribute("user");
        List<Address> addressList = addressService.selectAddress(user.getUserId());
        return RetType.retJson(RetJsonUtils.toJson(addressList));
    }
    @YWebPath("/addAddress")
    public RetType addAddress(String json,HttpSession session){
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>() {}.getType();
        Map<String, String> map = gson.fromJson(json, type);

        String newName = map.get("newName");
        String newAddress = map.get("newAddress");
        String newPhone = map.get("newPhone");
        String newMail = map.get("newMail");
        String newDefault = map.get("newDefault");
        User user = (User) session.getAttribute("user");

        Address address = new Address(0,user.getUserId(),newName,newAddress,newPhone,newMail,Integer.valueOf(newDefault));
        int i = addressService.insertAddress(address);
        System.out.println("add address id:"+i +" id:"+address.getAddrId());


        List<Address> addressList = addressService.selectAddress(user.getUserId());
        if ("1".equals(newDefault)){
            addressService.updataDefaultAddr(addressList.get(addressList.size()-1));
        }
        addressList = addressService.selectAddress(user.getUserId());
        return RetType.retJson(RetJsonUtils.toJson(addressList));
    }

    @YWebPath("/updataDefaultAddr")
    public RetType updataDefaultAddr(String addrId,HttpSession session){ //更新默认地址
        User user = (User) session.getAttribute("user");

        Address address = new Address();
        address.setUserId(user.getUserId());
        address.setAddrId(Integer.valueOf(addrId));

        addressService.updataDefaultAddr(address);
        return RetType.retEmpty();
    }


}
